﻿document.addEventListener('DOMContentLoaded', function () {
  var jsSwitch = document.getElementById('jsSwitch');

  // 向后台脚本发送消息以获取当前标签页的 JavaScript 状态
  /*   chrome.runtime.sendMessage({ action: 'getJavaScriptStatus' }, function(response) {
      var isEnabled = response.isEnabled;
      jsSwitch.checked = isEnabled;
    }, function(error) {
      console.error(error);
    }); */


  sendMessageToContentScript({ action: 'getJavaScriptStatus' }, function (response) {
    if (response) {
      var isEnabled = response.isEnabled;
      jsSwitch.checked = isEnabled;
    } else {
      console.log('## 未收到消息');
    }
  });


  // 监听开关按钮的变化
  jsSwitch.addEventListener('change', function() {
    var isEnabled = jsSwitch.checked;
    toggleJavaScript(isEnabled);
  });


// 切换 JavaScript 功能
/* function toggleJavaScript(isEnabled) {
  if (isEnabled) {
    enableJavaScript();
  } else {
    disableJavaScript();
  }
} */

});


// 切换 JavaScript 功能
function toggleJavaScript(isEnabled) {
  chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
    var currentTabId = tabs[0].id;
    var cspValue = isEnabled ? "script-src 'self';" : "script-src 'self' 'unsafe-inline';";
    chrome.tabs.sendMessage(currentTabId, { action: 'updateCSP', cspValue: cspValue });
  });
}
// 启用 JavaScript
function enableJavaScript() {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    var currentTabId = tabs[0].id;
    chrome.tabs.sendMessage(currentTabId, { action: 'enableJavaScript' });
  });
}

// 禁用 JavaScript
function disableJavaScript() {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    var currentTabId = tabs[0].id;
    chrome.tabs.sendMessage(currentTabId, { action: 'disableJavaScript' });
  });
}


function GetMessageFromBackground(data) {
  console.log("来自background~", data)
}

function sendMessageToContentScript(message, callback) {
  chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
      if (callback) callback(response);
    });
  });
}
